package com.project.servlet;

import com.project.bean.ProductBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Enumeration;

public class AddProduct extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            //将表单数据封装成商品对象
        ProductBean product = new ProductBean();
//        String name=req.getParameter("name");
//        product.setName(name);
//        product.setPrice(Integer.parseInt(req.getParameter("price")));
//        product.setCreateDate(LocalDate.parse(req.getParameter("date")));
//        product.setFactory(req.getParameter("factory"));
        fullBean(product,req);
        resp.getWriter().println(product);

    }

    private void fullBean(Object obj, HttpServletRequest req) {

        Enumeration<String> em = req.getParameterNames();
        while(em.hasMoreElements()){

            try {
            String name = em.nextElement();
                Field f= obj.getClass().getDeclaredField(name);
                f.setAccessible(true);
                String value = req.getParameter(name);
                if (f.getType()==String.class){
                    f.set(obj,value);
                }else if (f.getType()==int.class || f.getType()==Integer.class){
                    f.set(obj,Integer.parseInt(value));
                }else if (f.getType()==double.class ){
                    f.set(obj,Double.parseDouble(value));
                }else if (f.getType()==LocalDate.class){
                    f.set(obj,LocalDate.parse(value));
                }



            } catch (Exception e) {
                e.printStackTrace();
            }


        }



    }
}
